using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace VietThinks.Web.Mvc
{
    /// <summary>
    /// Represents a result that performs a transfer
    /// </summary>
    public class TransferResult : RedirectResult
    {
        public TransferResult(string url)
            : base(url)
        {
        }

        public TransferResult(RouteValueDictionary routeValues, RouteData routeData)
            : base(RouteUrl(routeValues, routeData))
        {
        }

        public TransferResult(object routeValues, RouteData routeData)
            : base(RouteUrl(routeValues, routeData))
        {
        }

        public TransferResult(object routeValues)
            : base(RouteUrl(routeValues, new RouteData()))
        {
        }

        private static string RouteUrl(RouteValueDictionary routeValues, RouteData routeData)
        {
            var requestContext = new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData);

            return new UrlHelper(requestContext).RouteUrl(routeValues);
        }

        private static string RouteUrl(object routeValues, RouteData routeData)
        {
            var requestContext = new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData);

            return new UrlHelper(requestContext).RouteUrl(routeValues);
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var httpContext = HttpContext.Current;

            httpContext.Session["OriginalRequestPath"] = httpContext.Request.Path;

            httpContext.RewritePath(Url, false);

            IHttpHandler httpHandler = new MvcHttpHandler();

            httpHandler.ProcessRequest(HttpContext.Current);

            httpContext.Session.Remove("OriginalRequestPath");
        }
    }
}
